package com.ckzp.plugins.sms.util;

import cn.hutool.core.util.StrUtil;
import com.ckzp.core.Results;
import com.ckzp.core.util.DateUtil;
import com.ckzp.core.util.RandomUtil;
import com.ckzp.plugins.sms.model.SysCaptcha;

import java.util.Date;

/**
 * Created by 51594 on 2023/11/3.
 */
public class SysCaptchaUtil {


    public static SysCaptchaUtil n() {
        return new SysCaptchaUtil();
    }

    /**
     * 写入VCODE
     *
     * @param mphone
     * @param v_code
     * @param times
     * @return
     */
    public Results createVcode(String mphone, String v_code, int times) {
        Results result = Results.n(0, "发送成功");
        SysCaptcha vcode = SysCaptcha.dao.findById(mphone);
        Date passdate = DateUtil.getAddDate(new Date(), times * 1000);
        Date curr = DateUtil.getAddDate(new Date(), -60 * 1000);
        if (vcode == null) {
            vcode = new SysCaptcha();
            vcode.set("mphone", mphone).set("vcode", v_code).set("cdate", new Date()).set("passdate", passdate).save();
        } else {
            vcode.set("vcode", v_code).set("cdate", new Date()).set("passdate", passdate).update();
        }
        return result;
    }


    /**
     * 写入VCODE
     *
     * @param mphone
     * @param times
     * @return
     */
    public int createVcode(String mphone, int times) {
        int v_code = RandomUtil.getInt(1000, 9999);
        SysCaptcha vcode = SysCaptcha.dao.findById(mphone);
        Date passdate = DateUtil.getAddDate(new Date(), times * 1000);
        if (vcode == null) {
            vcode = new SysCaptcha();
            vcode.set("mphone", mphone).set("vcode", v_code).set("cdate", new Date()).set("passdate", passdate).save();
        } else {
            vcode.set("vcode", v_code).set("cdate", new Date()).set("passdate", passdate).update();
        }
        return v_code;
    }

    /**
     * 写入VCODE
     *
     * @param mphone
     * @return
     */
    public int createVcode(String mphone) {
        return createVcode(mphone, 60);
    }

    /**
     * 验证VCODE
     *
     * @param mphone
     * @param v_code
     * @return
     */
    public boolean checkVcode(String mphone, String v_code) {
        if (StrUtil.isBlank(v_code)) return false;
        v_code = v_code.toUpperCase();
        SysCaptcha vcode = SysCaptcha.dao.findById(mphone);
        if (vcode != null) {
            if (vcode.mod.getStr("vcode", "").equals(v_code)) {
                vcode.delete();
                return true;
            }
        }
        return false;
    }

}
